package com.ny.zmb.openapi.controller;

import com.ny.zmb.openapi.controller.entity.Result;
import com.ny.zmb.openapi.service.IPmSmsService;
import com.ny.zmb.openapi.util.SmsUtil;
import com.ny.zmb.openapi.util.StringUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 *
 */
@RestController
@RequestMapping("ys/sms")
@CrossOrigin
public class SmsController {

    @Resource
    private IPmSmsService pmSmsService;
    /**
     * 发送验证码
     * @param mobile
     * @return
     */
    @GetMapping("sendPhone")
    public Result sendPhone(String mobile, HttpServletRequest request){
        if (StringUtil.isBlank(mobile)){
            return Result.fail("手机号不能为空");
        }
        if (mobile.length() != 11){
            return Result.fail("手机号不合法");
        }
        String ipAddress = getIpAddress(request);
        String random = SmsUtil.createRandom();
        pmSmsService.saveSendPhone(mobile,random,ipAddress);
        SmsUtil.sendSmsMsg(mobile,random);
        return Result.ok(random);
    }

    /**
     * 验证验证码
     * @param mobile
     * @param code
     * @return
     */
    @GetMapping("verifyMobile")
    public Result verifyMobile(String mobile,String code){
        if (pmSmsService.verifyMobile(mobile,code)){
            return Result.ok();
        }
        return Result.fail("验证码已过期");
    }

    /**
     * 获取ip
     * @param request
     * @return
     */
    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

